package kr.hkit.powerjava.alone.dao;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;

import kr.hkit.powerjava.alone.vo.Account;

public class AccountDao implements BankInterfaceDao<Account> {
	private ArrayList<Account> lists;
	private static String File_NAME = "AccountList.data";
	
	@Override
	public void insertItem(Account item) {
		if(!lists.contains(item)){
			lists.add(item);
		}else{
			System.out.println("중복된 데이터");
		}
	}
	@Override
	public void deleteItem(Account item) {
		lists.remove(item);
	}
	@Override
	public void updateItem(Account item) {
		lists.set(lists.indexOf(item), item);
	}
	@Override
	public Account searchItem(Account item) {
		return lists.get(lists.indexOf(item));
	}
	@Override
	public void prnItemList(Comparator<Account> comp) {
		if(comp==null){
			Collections.sort(lists);
		}else{
			Collections.sort(lists, comp);
		}
		for (Account acc : lists) {
			System.out.println(acc);
		}
	}
	@Override
	public void loadFile() {
		ObjectInputStream ois = null;
		
		try {
			ois = new ObjectInputStream(new BufferedInputStream(new FileInputStream(AccountDao.File_NAME)));
			lists=((ArrayList<Account>) ois.readObject());
		} catch (FileNotFoundException e) {
			try {
				new File(AccountDao.File_NAME).createNewFile();
				lists = new ArrayList<>();
			} catch (IOException e1) {}
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			if(ois!=null)try{ois.close();}catch(Exception e){}
		}
	}
	@Override
	public void saveFile() {
		ObjectOutputStream oos = null;
		try {
			oos = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(AccountDao.File_NAME)));
			oos.writeObject(lists);
		}catch (IOException e) {
			e.printStackTrace();
		}finally{
			if(oos!=null)try{oos.close();}catch(Exception e){}
		}
		
	}
	
	
}
